package com.example.contactapp;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Profile;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.contactapp.adapters.DetailSmsAdapter;
import com.example.contactapp.adapters.SmsAdapter;
import com.example.contactapp.objects.SmsObject;
import com.example.contactapp.providers.SMSThread;

public class SmsDetailActivity extends BaseActivity implements OnClickListener {
	private ListView myLv;
	private ArrayList<SmsObject> myArray;
	private DetailSmsAdapter myAdapter;
	private String myAddress;
	private EditText myEdtSMS;
	private String myAvatar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail_sms);
		//getOwnerPhone();
		initViews();
		initProperties();
		initListeners();
	}

	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		myLv = (ListView) findViewById(R.id.lv);
		myEdtSMS = (EditText) findViewById(R.id.ed_sms);
		myAddress = getIntent().getStringExtra("ADDRESS");
		((TextView) findViewById(R.id.tv_address)).setText(myAddress);
	}

	@Override
	protected void initListeners() {
		// TODO Auto-generated method stub
		((ImageView) findViewById(R.id.img_send_sms)).setOnClickListener(this);
	}

	@Override
	protected void initProperties() {
		// TODO Auto-generated method stub
		myArray = new ArrayList<SmsObject>();
		myArray = SmsAdapter.curSMSES;
		myAdapter = new DetailSmsAdapter(this, myArray);
		myLv.setAdapter(myAdapter);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.img_send_sms) {
			sendSMS(myAddress, myEdtSMS.getText().toString());
		}
	}

	public void getOwnerPhone() {
		/*TelephonyManager info = (TelephonyManager) getApplicationContext()
				.getSystemService(Context.TELEPHONY_SERVICE);
		String phoneNumber = info.getLine1Number();*/
		final String[] SELF_PROJECTION = new String[] {Phone.NUMBER,
                Phone.DISPLAY_NAME, };
		Cursor cursor = this.getContentResolver().query(
                Profile.CONTENT_URI, null, null, null, null);
		if(cursor.moveToFirst()){
			Toast.makeText(this, cursor.getString(0), Toast.LENGTH_SHORT).show();
		}
		/*ContentResolver cr = this.getContentResolver();
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
				Uri.encode(phoneNumber));
		Cursor cursor = cr.query(uri, new String[] { PhoneLookup.DISPLAY_NAME,
				PhoneLookup.PHOTO_URI }, null, null, null);
		if (cursor == null) {
			return;
		}
		String contactName = phoneNumber;
		if (cursor.moveToFirst()) {
			myAvatar = cursor.getString(cursor
					.getColumnIndex(PhoneLookup.PHOTO_URI));
			Toast.makeText(this, myAvatar, Toast.LENGTH_SHORT).show();
		} else {
			myAvatar = "";
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}*/
	}

	private void sendSMS(final String phoneNumber, final String message) {
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";
		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
				SENT), 0);
		PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
				new Intent(DELIVERED), 0);
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					ContentValues values = new ContentValues();
					values.put("address", phoneNumber);// txtPhoneNo.getText().toString());
					values.put("body", message);
					getContentResolver().insert(
							Uri.parse("content://sms/sent"), values);
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Toast.makeText(getBaseContext(), "Generic failure",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Toast.makeText(getBaseContext(), "No service",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Toast.makeText(getBaseContext(), "Null PDU",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Toast.makeText(getBaseContext(), "Radio off",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(SENT));
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS sent.",
							Toast.LENGTH_SHORT).show();
					SmsObject object = new SmsObject();
					object.setAddress(myAddress);
					object.setBodySms(message);
					object.setTime(new Date().getTime());
					object.setType(2);
					myArray.add(0, object);
					myAdapter.notifyDataSetChanged();
					try {
						myLv.setSelection(myArray.size()-1);
						myEdtSMS.setText("");
					} catch (Exception e) {
						// TODO: handle exception
					}
					
					break;
				case Activity.RESULT_CANCELED:
					Toast.makeText(getBaseContext(), "SMS not delivered",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(DELIVERED));

		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
	}

}
